Methods __enter__
and __exit__
make it possible to implement objects which can be used as the expression of a
with
statement:
with MyContextManager() as c :
... # do something with c
This statement can be rewritten as a try...finally
and an explicit call to the __enter__
and __exit__
methods:
c = MyContextManager()
c.__enter__()
try:
... # do something with c
finally:
c.__exit__()
The __exit__
is the method of a statement context manager which is called when exiting the runtime context related to this object.
If an exception is supplied as an argument, its propagation can be suppressed by having the method return a truthy value. Otherwise, the exception
will be processed normally upon exit from the method.
The special method __exit__
should only raise an
exception when it fails. It should never raise the provided exception, it is the caller’s responsibility. The __exit__
method can filter
provided exceptions by simply returning True or False. Raising this exception will make the stack trace difficult to understand.